package org.example;

/**
 * 反转链表
 */
public class Solution23 {

    public static class ListNode {

        int val;

        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

    }

    public ListNode reverseList(ListNode head) {
        // 初始化prev, curr分别指向null和头节点
        ListNode curr = head;
        ListNode prev = null;

        while (curr != null) {
            // 暂时存储后继节点
            ListNode temp = curr.next;

            // 指向null，断开节点
            curr.next = prev;

            // prev向前移动
            prev = curr;

            // curr 向前移动
            curr = temp;
        }

        return prev;
    }

}
